//
//  BNRDrawView.m
//  Quiz
//
//  Created by YaoJacob on 15/11/5.
//  Copyright © 2015年 Roger. All rights reserved.
//

#import "BNRDrawView.h"
#import "BNRLine.h"

@interface BNRDrawView () <UIGestureRecognizerDelegate>
//@property (nonatomic,strong) BNRLine* currentLine;
@property (nonatomic, strong) NSMutableDictionary *lineInProcess;
@property (nonatomic, strong) NSMutableArray *finishedLines;
@property (nonatomic, strong) UIPanGestureRecognizer *moveRecognizer;

@property (nonatomic, weak) BNRLine* selectedLine;
@end

@implementation BNRDrawView
-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        self.lineInProcess = [[NSMutableDictionary alloc]init];
        self.finishedLines = [[NSMutableArray alloc]init];
        self.backgroundColor = [UIColor grayColor];
        
        self.multipleTouchEnabled = YES;
        
        //手势识别
        UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap:)];
        doubleTapRecognizer.numberOfTapsRequired = 2;
        doubleTapRecognizer.delaysTouchesBegan = YES;//延迟response链子
        [self addGestureRecognizer:doubleTapRecognizer];
        
        UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(Tap:)];
        tapRecognizer.delaysTouchesBegan = YES;//延迟response链子
        [tapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];
        [self addGestureRecognizer:tapRecognizer];
        
        UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
        tapRecognizer.delaysTouchesBegan = YES;//延迟response链子
        [self addGestureRecognizer:longPressRecognizer];
        
        //pan--Error.
//        self.moveRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(moveLine:)];
//        self.moveRecognizer.delegate = self;
//        //self.moveRecognizer.cancelsTouchesInView = NO;
//        [self addGestureRecognizer:self.moveRecognizer];
    }
    return self;
}

-(void)drawRect:(CGRect)rect
{
    [[UIColor blackColor] set];
    for (BNRLine* line in self.finishedLines) {
        [self stokeLine:line];
    }
    
    [[UIColor redColor] set];
    for (NSValue *key in self.lineInProcess) {
        [self stokeLine:self.lineInProcess[key]];
    }
    if (self.selectedLine) {
        [[UIColor greenColor] set];
        [self stokeLine:self.selectedLine];
    }
}

-(void)stokeLine:(BNRLine*)line
{
    UIBezierPath *bp = [UIBezierPath bezierPath];
    bp.lineWidth = 10;
    bp.lineCapStyle = kCGLineCapRound;
    
    
    [bp moveToPoint:line.begin];
    [bp addLineToPoint:line.end];
    [bp stroke];
}

#pragma @"Draw events."
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
    
    //    UITouch *t = [touches anyObject];
    //    CGPoint location = [t locationInView:self];
    //
    //    self.currentLine = [[BNRLine alloc]init];
    //    self.currentLine.begin = location;
    //    self.currentLine.end = location;
    
    for (UITouch * t in touches) {
        
        CGPoint location = [t locationInView:self];
        
        BNRLine* line = [[BNRLine alloc]init];
        line.begin = location;
        line.end = location;
        
        NSValue* key = [NSValue valueWithNonretainedObject:t];
        self.lineInProcess[key] = line;
    }
    
    [self setNeedsDisplay];
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
    
    //    UITouch *t = [touches anyObject];
    //    CGPoint location = [t locationInView:self];
    //
    //    self.currentLine.end = location;
    
    for (UITouch * t in touches) {
        
        CGPoint location = [t locationInView:self];
        
        NSValue* key = [NSValue valueWithNonretainedObject:t];
        
        BNRLine* line = self.lineInProcess[key];
        line.end = location;
    }
    [self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
    
    for (UITouch * t in touches) {
        NSValue* key = [NSValue valueWithNonretainedObject:t];
        
        BNRLine* line = self.lineInProcess[key];
        if(line)
        {
            [self.finishedLines addObject:line];
        }
    }
    
    [self.lineInProcess removeAllObjects];
    
    [self setNeedsDisplay];
}

-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
    
    [self.lineInProcess removeAllObjects];
    
    [self setNeedsDisplay];
    
}

#pragma 手势识别

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

-(void)Tap:(UIGestureRecognizer *)gr
{
    NSLog(@"Tap");
    
    CGPoint point = [gr locationInView:self];
    self.selectedLine = [self lineAtPointAround:point];
    
    if (self.selectedLine) {
        [self becomeFirstResponder];
        
        UIMenuController *menu = [UIMenuController sharedMenuController];
        UIMenuItem *delItem = [[UIMenuItem alloc] initWithTitle:@"Del" action:@selector(deleLine:)];
        menu.menuItems = @[delItem];
        
        [menu setTargetRect:CGRectMake(point.x, point.y, 2, 2) inView:self];
        [menu setMenuVisible:YES animated:YES];
    }
    else
    {
        [[UIMenuController sharedMenuController]setMenuVisible:NO animated:YES];
    }
    
    [self setNeedsDisplay];
}

-(void)doubleTap:(UIGestureRecognizer *)gr
{
    NSLog(@"doubleTap");
    
    [self.lineInProcess removeAllObjects];
    [self.finishedLines removeAllObjects];
    
    [self setNeedsDisplay];
}

-(BNRLine*)lineAtPointAround:(CGPoint)p
{
    for (BNRLine *l in self.finishedLines) {
        CGPoint start = l.begin;
        CGPoint end = l.end;
        
        for (float t = 0.0; t <= 1.0; t+=0.05) {
            float x = start.x + t* (end.x - start.x);
            float y = start.y + t *(end.y - start.y);
            
            if (hypotf(x-p.x, y - p.y) < 20.0) {
                return l;
            }
        }
    }
    
    return nil;
}

-(void)deleLine:(id)sender
{
    [self.finishedLines removeObject:self.selectedLine];
    
    [self setNeedsDisplay];
}

-(void)longPress:(UIGestureRecognizer *)gr
{
    NSLog(@"longPress");
    
    if (gr.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [gr locationInView:self];
        self.selectedLine = [self lineAtPointAround:point];
        
        if (self.selectedLine) {
            [self.lineInProcess removeAllObjects];
        }
    }
    else if(gr.state == UIGestureRecognizerStateEnded)
    {
        self.selectedLine = nil;
    }
    
    [self setNeedsDisplay];
}

//pan
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if (gestureRecognizer == self.moveRecognizer) {
        return YES;
    }
    
    return NO;
}

-(void)moveLine:(UIPanGestureRecognizer *)gr
{
    NSLog(@"moveLine");
    
    if(!self.selectedLine)
    {
        return;
    }
    
    if (gr.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gr translationInView:self];
        
        CGPoint begin = self.selectedLine.begin;
        CGPoint end = self.selectedLine.end;
        begin.x += translation.x;
        begin.y += translation.y;
        end.x += translation.x;
        end.y += translation.y;
        
        self.selectedLine.begin = begin;
        self.selectedLine.end = end;
        
            [self setNeedsDisplay];
        
        [gr setTranslation:CGPointZero inView:self];
    }
}
@end
